import React, { useState, useEffect } from 'react';
import { 
  Typography, 
  Row, 
  Col, 
  List, 
  Card, 
  Input, 
  Button, 
  Spin, 
  Avatar, 
  Divider,
  Select,
  Empty 
} from 'antd';
import { 
  SendOutlined, 
  UserOutlined, 
  MessageOutlined, 
  EllipsisOutlined 
} from '@ant-design/icons';
import chatService from '../api/chatService';
import contactsService from '../api/contactsService';

const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

const ChatPage = () => {
  const [contacts, setContacts] = useState([]);
  const [selectedContactId, setSelectedContactId] = useState(null);
  const [messages, setMessages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [messageText, setMessageText] = useState('');
  const [optimizeLoading, setOptimizeLoading] = useState(false);
  const [suggestions, setSuggestions] = useState([]);
  const [relationshipTypes, setRelationshipTypes] = useState([]);
  const [chatGoals, setChatGoals] = useState([]);
  const [selectedRelationship, setSelectedRelationship] = useState('');
  const [selectedGoal, setSelectedGoal] = useState('');

  // 获取联系人列表
  useEffect(() => {
    const fetchContacts = async () => {
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          const mockContacts = [
            { id: '1', name: '张三', avatar: null, last_message: '明天我们什么时候见面？', time: '10:30', unread: 2 },
            { id: '2', name: '李四', avatar: null, last_message: '收到了，我会准时参加。', time: '昨天', unread: 0 },
            { id: '3', name: '工作群', avatar: null, last_message: '已经上传了会议纪要，请查收。', time: '前天', unread: 5 },
            { id: '4', name: '王五', avatar: null, last_message: '这个周末有空吗？一起吃个饭？', time: '周一', unread: 0 }
          ];
          setContacts(mockContacts);
        }, 500);
        
        // 实际API调用示例：
        // const contactsData = await contactsService.getContacts();
        // setContacts(contactsData);
      } catch (error) {
        console.error('获取联系人失败:', error);
      }
    };

    fetchContacts();
  }, []);

  // 获取关系类型和聊天目标
  useEffect(() => {
    const fetchRelationshipData = async () => {
      try {
        // 模拟数据 - 实际应用中应使用API
        setTimeout(() => {
          setRelationshipTypes([
            { id: 'friend', name: '朋友' },
            { id: 'colleague', name: '同事' },
            { id: 'family', name: '家人' },
            { id: 'client', name: '客户' },
            { id: 'superior', name: '上级' },
            { id: 'subordinate', name: '下级' }
          ]);
          
          setChatGoals([
            { id: 'social', name: '社交聊天' },
            { id: 'work_report', name: '工作汇报' },
            { id: 'negotiate', name: '协商事务' },
            { id: 'solve_problem', name: '解决问题' },
            { id: 'maintain_relationship', name: '维系关系' }
          ]);
        }, 500);
        
        // 实际API调用示例：
        // const relationshipTypes = await contactsService.getRelationshipTypes();
        // const chatGoals = await contactsService.getChatGoals();
        // setRelationshipTypes(relationshipTypes);
        // setChatGoals(chatGoals);
      } catch (error) {
        console.error('获取关系数据失败:', error);
      }
    };

    fetchRelationshipData();
  }, []);

  // 获取聊天记录
  useEffect(() => {
    if (selectedContactId) {
      const fetchMessages = async () => {
        setLoading(true);
        try {
          // 模拟数据 - 实际应用中应使用API
          setTimeout(() => {
            const mockMessages = [
              { id: 1, content: '你好，最近怎么样？', time: '昨天 14:23', is_self: false },
              { id: 2, content: '我很好，谢谢关心！你呢？', time: '昨天 14:25', is_self: true },
              { id: 3, content: '我也不错，最近在忙一个新项目', time: '昨天 14:30', is_self: false },
              { id: 4, content: '听起来很棒！是什么项目？', time: '昨天 14:32', is_self: true },
              { id: 5, content: '一个关于人工智能的应用，有机会我们可以详细聊聊', time: '昨天 14:35', is_self: false },
              { id: 6, content: '当然，我很感兴趣。这周末有空一起吃个饭吗？', time: '昨天 14:40', is_self: true },
              { id: 7, content: '好啊，周六中午怎么样？', time: '昨天 14:45', is_self: false },
              { id: 8, content: '周六中午可以，地点你来选吧', time: '昨天 14:50', is_self: true }
            ];
            setMessages(mockMessages);
            setLoading(false);
          }, 800);
          
          // 实际API调用示例：
          // const messagesData = await chatService.getChatHistory(selectedContactId);
          // setMessages(messagesData);
        } catch (error) {
          console.error('获取聊天记录失败:', error);
          setLoading(false);
        }
      };

      fetchMessages();
      
      // 获取当前联系人的关系设置
      const fetchContactRelationship = async () => {
        try {
          // 模拟数据 - 实际应用中应使用API
          setTimeout(() => {
            if (selectedContactId === '1') {
              setSelectedRelationship('friend');
              setSelectedGoal('social');
            } else if (selectedContactId === '2') {
              setSelectedRelationship('colleague');
              setSelectedGoal('work_report');
            } else {
              setSelectedRelationship('');
              setSelectedGoal('');
            }
          }, 300);
          
          // 实际API调用示例：
          // const contactDetail = await contactsService.getContactDetail(selectedContactId);
          // setSelectedRelationship(contactDetail.relationship_type || '');
          // setSelectedGoal(contactDetail.chat_goal || '');
        } catch (error) {
          console.error('获取联系人关系设置失败:', error);
        }
      };
      
      fetchContactRelationship();
    } else {
      setMessages([]);
    }
  }, [selectedContactId]);

  // 优化消息
  const handleOptimize = async () => {
    if (!messageText.trim() || !selectedContactId || !selectedRelationship || !selectedGoal) return;
    
    setOptimizeLoading(true);
    setSuggestions([]);
    
    try {
      // 模拟数据 - 实际应用中应使用API
      setTimeout(() => {
        const mockSuggestions = [
          {
            id: 1,
            content: messageText.trim() + '，期待与你的交流！',
            explanation: '添加更友好的表达，增强互动性'
          },
          {
            id: 2,
            content: messageText.trim() + '，你怎么看？',
            explanation: '增加提问，鼓励对方回应'
          },
          {
            id: 3,
            content: '我认为' + messageText.trim() + '，不知你是否同意？',
            explanation: '加入个人观点，同时表达尊重对方意见'
          }
        ];
        
        setSuggestions(mockSuggestions);
        setOptimizeLoading(false);
      }, 1000);
      
      // 实际API调用示例：
      // const suggestionsData = await chatService.getOptimizationSuggestions(
      //   messageText,
      //   selectedContactId,
      //   selectedRelationship,
      //   selectedGoal
      // );
      // setSuggestions(suggestionsData);
    } catch (error) {
      console.error('获取优化建议失败:', error);
      setOptimizeLoading(false);
    }
  };

  // 应用建议
  const applySuggestion = (suggestion) => {
    setMessageText(suggestion.content);
    setSuggestions([]);
  };

  // 发送消息
  const handleSendMessage = () => {
    if (!messageText.trim() || !selectedContactId) return;
    
    // 在实际应用中，这里应该调用API保存消息
    const newMessage = {
      id: Date.now(),
      content: messageText.trim(),
      time: '刚刚',
      is_self: true
    };
    
    setMessages([...messages, newMessage]);
    setMessageText('');
    setSuggestions([]);
    
    // 实际API调用示例：
    // await chatService.saveMessage({
    //   contact_id: selectedContactId,
    //   content: messageText.trim(),
    //   is_self: true
    // });
  };

  return (
    <div>
      <Title level={2}>聊天</Title>
      <Paragraph>
        与联系人交流，获取优化建议，提高沟通效果。
      </Paragraph>
      
      <Row gutter={16}>
        {/* 联系人列表 */}
        <Col span={6}>
          <Card title="联系人" style={{ height: 'calc(100vh - 250px)', overflow: 'auto' }}>
            {contacts.length > 0 ? (
              <List
                dataSource={contacts}
                renderItem={contact => (
                  <List.Item 
                    key={contact.id}
                    onClick={() => setSelectedContactId(contact.id)}
                    className={`contact-item ${selectedContactId === contact.id ? 'active' : ''}`}
                    style={{ cursor: 'pointer' }}
                  >
                    <List.Item.Meta
                      avatar={<Avatar icon={<UserOutlined />} />}
                      title={contact.name}
                      description={
                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Text ellipsis style={{ maxWidth: '70%' }}>{contact.last_message}</Text>
                          <Text type="secondary">{contact.time}</Text>
                        </div>
                      }
                    />
                    {contact.unread > 0 && (
                      <div style={{ 
                        background: '#1890ff', 
                        color: 'white', 
                        borderRadius: '50%', 
                        width: 20, 
                        height: 20, 
                        display: 'flex', 
                        alignItems: 'center', 
                        justifyContent: 'center',
                        fontSize: 12
                      }}>
                        {contact.unread}
                      </div>
                    )}
                  </List.Item>
                )}
              />
            ) : (
              <Empty description="暂无联系人" />
            )}
          </Card>
        </Col>
        
        {/* 聊天窗口 */}
        <Col span={12}>
          <Card 
            title={selectedContactId ? contacts.find(c => c.id === selectedContactId)?.name : "选择联系人开始聊天"}
            style={{ height: 'calc(100vh - 250px)', display: 'flex', flexDirection: 'column' }}
          >
            {selectedContactId ? (
              <>
                {/* 聊天记录 */}
                <div className="chat-history" style={{ flex: 1, overflow: 'auto' }}>
                  {loading ? (
                    <div style={{ textAlign: 'center', padding: '20px 0' }}>
                      <Spin />
                    </div>
                  ) : (
                    messages.map(message => (
                      <div key={message.id} style={{ marginBottom: 16, display: 'flex', flexDirection: 'column', alignItems: message.is_self ? 'flex-end' : 'flex-start' }}>
                        <div className={`chat-message ${message.is_self ? 'message-self' : 'message-other'}`}>
                          {message.content}
                        </div>
                        <div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>
                          {message.time}
                        </div>
                      </div>
                    ))
                  )}
                </div>
                
                {/* 输入区域 */}
                <div className="message-input">
                  <TextArea 
                    rows={3} 
                    value={messageText}
                    onChange={(e) => setMessageText(e.target.value)}
                    placeholder="输入消息..."
                  />
                  <div style={{ marginTop: 16, display: 'flex', justifyContent: 'space-between' }}>
                    <Button 
                      onClick={handleOptimize}
                      disabled={!messageText.trim() || !selectedRelationship || !selectedGoal}
                      loading={optimizeLoading}
                    >
                      优化消息
                    </Button>
                    <Button 
                      type="primary" 
                      icon={<SendOutlined />} 
                      onClick={handleSendMessage}
                      disabled={!messageText.trim()}
                    >
                      发送
                    </Button>
                  </div>
                  
                  {/* 优化建议 */}
                  {suggestions.length > 0 && (
                    <div className="suggestion-container">
                      <div className="suggestion-title">优化建议:</div>
                      {suggestions.map(suggestion => (
                        <div 
                          key={suggestion.id} 
                          className="suggestion-item"
                          onClick={() => applySuggestion(suggestion)}
                        >
                          <div>{suggestion.content}</div>
                          <div style={{ fontSize: 12, color: '#999' }}>{suggestion.explanation}</div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </>
            ) : (
              <Empty description="请选择联系人开始聊天" style={{ margin: 'auto' }} />
            )}
          </Card>
        </Col>
        
        {/* 聊天关系设置面板 */}
        <Col span={6}>
          <Card title="聊天设置" style={{ height: 'calc(100vh - 250px)' }}>
            {selectedContactId ? (
              <div>
                <div className="relationship-form-item">
                  <Text strong>关系类型:</Text>
                  <Select
                    style={{ width: '100%', marginTop: 8 }}
                    value={selectedRelationship}
                    onChange={setSelectedRelationship}
                    placeholder="选择关系类型"
                  >
                    {relationshipTypes.map(type => (
                      <Option key={type.id} value={type.id}>{type.name}</Option>
                    ))}
                  </Select>
                </div>
                
                <div className="relationship-form-item">
                  <Text strong>聊天目标:</Text>
                  <Select
                    style={{ width: '100%', marginTop: 8 }}
                    value={selectedGoal}
                    onChange={setSelectedGoal}
                    placeholder="选择聊天目标"
                  >
                    {chatGoals.map(goal => (
                      <Option key={goal.id} value={goal.id}>{goal.name}</Option>
                    ))}
                  </Select>
                </div>
                
                <div className="relationship-form-item">
                  <Text strong>沟通提示:</Text>
                  <div style={{ marginTop: 8, padding: 8, background: '#f5f5f5', borderRadius: 4 }}>
                    {selectedRelationship && selectedGoal ? (
                      <ul style={{ paddingLeft: 20, margin: 0 }}>
                        <li>与{relationshipTypes.find(t => t.id === selectedRelationship)?.name}交流时保持适当的礼貌和距离</li>
                        <li>目标为{chatGoals.find(g => g.id === selectedGoal)?.name}，注重表达清晰和重点突出</li>
                        <li>定期互动以维护良好关系</li>
                      </ul>
                    ) : (
                      <Text type="secondary">请选择关系类型和聊天目标获取提示</Text>
                    )}
                  </div>
                </div>
              </div>
            ) : (
              <Empty description="请选择联系人进行设置" />
            )}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default ChatPage;